import axios from 'axios';
import config from './config';
import CryptoJS from 'crypto-js';

const PASSWORD_SECRET = 'password_secret_456';

const apiClient = axios.create({
  baseURL: config.API_BASE_URL,
  headers: { 'Content-Type': 'application/json' }
});

// 获取所有论坛文章
// 获取所有论坛文章
export const getForumArticles = async () => {
  try {
    // 从 localStorage 中获取 token
    const token = localStorage.getItem('token');
    if (!token) return { success: false, message: '请先登录' };

    // 发送 GET 请求，带上 Authorization header
    const response = await apiClient.get('/api/forum_articles', {
      headers: { 'Authorization': `Bearer ${token}` }
    });

    // console.log(response.data, 'response.datacsacascas');
    // 返回获取的文章数据
    return { success: true, articles: response.data };
  } catch (error) {
    console.error('获取论坛文章失败:', error);
    // 如果没有返回自定义的错误信息，返回通用错误信息
    return { success: false, message: error.response?.data?.message || '获取失败' };
  }
};

// 根据文章 ID 获取文章详情
export const getForumArticleById = async (articleId) => {
  console.log(articleId, 'articleId');
  try {
    const token = localStorage.getItem('token');
    if (!token) return { success: false, message: '请先登录' };

    const response = await apiClient.get(`/api/forum_articles/${articleId}`, {
      headers: { 'Authorization': `Bearer ${token}` }
    });

    return { success: true, article: response.data };
  } catch (error) {
    console.error(`获取文章（ID: ${articleId}）详情失败:`, error);
    return { success: false, message: error.response?.data?.message || '获取失败' };
  }
};



// 插入新论坛文章
export const postForumArticle = async (articleData) => {
  try {
    // 从 localStorage 中获取 token
    console.log(articleData, 'articleData');
    const token = localStorage.getItem('token');
    if (!token) return { success: false, message: '请先登录' };

    // 发送 POST 请求，带上 Authorization header 和请求体
    const response = await apiClient.post('/api/forum_articles', articleData, {
      headers: { Authorization: `Bearer ${token}` }
    });

    return { success: true, articleId: response.data.articleId };
  } catch (error) {
    console.error('发布文章失败:', error);
    return {
      success: false,
      message: error.response?.data?.message || '发布失败'
    };
  }
};

// 根据文章id获取评论
export const getCommentsByArticleId = async (articleId) => {
  // 从 localStorage 中获取 token
  console.log(articleId, 'articleData;oi;io');
  const token = localStorage.getItem('token');
  if (!token) return { success: false, message: '请先登录' };


  try {
    const response = await apiClient.get(`/api/article_comments/${articleId}`);
    return { success: true, comments: response.data.comments };
  } catch (error) {
    console.error('获取评论失败:', error);
    return { success: false, message: '获取评论失败', error };
  }
};


// 插入文章评论
export const postArticleComment = async (commentData) => {
  try {
    const token = localStorage.getItem('token');
    if (!token) return { success: false, message: '请先登录' };

    const response = await apiClient.post('/api/article_comments', commentData, {
      headers: { Authorization: `Bearer ${token}` }
    });

    return {
      success: true,
      commentId: response.data.commentId,
      message: response.data.message
    };
  } catch (error) {
    console.error('插入评论失败:', error);
    return {
      success: false,
      message: error.response?.data?.message || '评论发布失败'
    };
  }
};


// 根据用户id获取用户文章列表
export const getUserArticleArrApi = async (userId) => {
  try {
    const token = localStorage.getItem('token');
    if (!token) return { success: false, message: '请先登录' };

    const response = await apiClient.get(`/api/articles/user/${userId}`, {
      headers: { 'Authorization': `Bearer ${token}` }
    });

    return { success: true, articles: response.data };
  } catch (error) {
    console.error('获取论坛文章失败:', error);
    return {
      success: false,
      message: error.response?.data?.message || error.message || '网络错误，请稍后重试'
    };
  }
};

// 删除文章
export const deleteArticleApi = async (userId, articleId) => {
  try {
    const token = localStorage.getItem('token');
    if (!token) return { success: false, message: '请先登录' };

    const response = await apiClient.delete(`/api/articles/user/${userId}/${articleId}`, {
      headers: { 'Authorization': `Bearer ${token}` }
    });

    return response.data;
  } catch (error) {
    console.error('删除文章失败:', error);
    return { success: false, message: error.response?.data?.error || '删除失败' };
  }
};


// 更新文章
export const updateArticleApi = async (userId, articleId, articleData) => {
  try {
    const token = localStorage.getItem('token');
    const response = await apiClient.put(
      `/api/articles/user/${userId}/${articleId}`,
      articleData,
      {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      }
    );
    return response.data;
  } catch (error) {
    console.error('更新失败:', error);
    return {
      success: false,
      message: error.response?.data?.error || '更新失败'
    };
  }
};


